package com.wanshi.servlet;

import com.wanshi.entity.Order;
import com.wanshi.entity.Product;
import com.wanshi.entity.User;
import com.wanshi.service.CartService;
import com.wanshi.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/*
根据yonghuid 查询购物车商品
1   订单表插入 1条记录

2  购物车表 根据用户id 清除记录

3  订单项表 插入记录

4 商品   相应商品减去库存

 */
@WebServlet("/order/addOrder")
public class addOrder extends HttpServlet {
    CartService cartService = new CartService();

    private OrderService orderService = new OrderService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String sheng = request.getParameter("sheng");
        sheng = sheng.substring(  sheng.indexOf(":")+1 );

        String shi = request.getParameter("shi");
        shi = shi.substring(  shi.indexOf(":")+1 );
        String xian = request.getParameter("xian");
        String receiveinfo = request.getParameter("receiveinfo");

        String address = sheng+shi+xian+receiveinfo;

        Order order = new Order();

        String uuid = UUID.randomUUID().toString().replace("-","");
        order.setId(uuid);

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Map<Product,Integer> map = cartService.findCartByUserId(user.getId()+"");
        Set<Map.Entry<Product, Integer>> entries = map.entrySet();
        double sum = 0;
        for(Map.Entry<Product, Integer> entry:entries){
            Product prod = entry.getKey();
            Integer num = entry.getValue();
            sum += prod.getPrice()*num;
        }
        order.setMoney(sum);

        order.setPaystate(0);
        order.setReceinfo(address);
        order.setUser_id(user.getId());
        order.setState(0);


        /*id varchar(50) NOT NULL // uuid
        money double NULL         //money  算出来
        paystate int(11) NULL(0未支付，1已支付，2 删除) //0
        receinfo varchar(80) NULL    //address
        add_time timestamp NOT NULL  // null
        user_id int(11) NULL    // 可以从session中获取
        state int(5) NULL*/    //是否删除0

        orderService.addOrder(order);

        response.sendRedirect(request.getContextPath()+"/index.jsp");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

